// store/pages/goods/detail.js
const GoodsService = require('../../../services/goods');
const AddressService = require('../../../services/address');
const storeService = require('../../../services/store.js');
const CartService = require('../../../services/cart.js');
import { areaList } from '@vant/area-data';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: 0,
        goods: null,
        images: [],
        currentPrice: null,
        saleSpecsFormId:[],

        buyFormVisible: false,
        selectSpecs: [],

        quantity: 1,

        // SKU相关
        selectedSku: null,
        skuStock: 0,

        // 地址相关
        defaultAddress: null,
        showAddressForm: false,
        addressForm: {
            name: '',
            phone: '',
            province: '',
            city: '',
            district: '',
            detail: '',
            region: '',
            isDefault: true
        },

        // 地区选择器
        showRegion: false,
        areaList,

        // 自提点列表
        pickUpPointList: [],
        defaultPickUpPoint: null,
        expressType: 'pickUpPoint', // 快递类型 pickUpPoint 自提点 express 快递 

        // 加入购物车
        addToCartVisible: false,
        addToCartForm: {
            quantity: 1,
            spec: '',
            goods_id: 0,
        },

        timeData: {},
        comments: [],

        steps:[
            {
                text: '开始',
                desc:'09-09'
              },
              {
                text: '预售中',
              },
              {
                text: '结束',
                desc:'09-30'
              },
              {
                text: '已发货',
              }
        ],
        active: 1
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            id: options.id
        })

        this.getGoodsDetail();
        this.getDefaultAddress();

        // 获取自提点列表
        this.getPickUpPointList();
        this.getStoreGoodsPings();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    async getStoreGoodsPings() {
        const { id } = this.data;
        try {
            const result = await GoodsService.pings({
                id: id,
                showLoading: true
            });


            this.setData({
                comments: result.data.list || []
            });
        } catch (error) {
            console.error('获取商家点评列表失败:', error);
        }
    },

    async getGoodsDetail() {
        const res = await GoodsService.getGoodsDetail(this.data.id);
        if (res.success) {
            this.setData({
                goods: res.data.goods,
                images: res.data.images,
                currentPrice: res.data.currentPrice,
                saleSpecsFormId: res.data.saleSpecsFormId
            });
        }
    },



    /**
     * 获取自提点列表
     */
    async getPickUpPointList() {
        const result = await storeService.pickUpPointList();
        if (result.success) {
            this.setData({
                pickUpPointList: result.data,
                defaultPickUpPoint: result.data[0] || null
            });
        }
    },

    /**
     * 获取用户默认地址
     */
    async getDefaultAddress() {
        try {
            const result = await AddressService.getAddressList({
                page: 1,
                pageSize: 10,
                showLoading: false
            });

            if (result.success && result.data && result.data.list) {
                // 查找默认地址
                const defaultAddress = result.data.list.find(address => address.is_default == 1);
                this.setData({
                    defaultAddress: defaultAddress || null
                });
            }
        } catch (error) {
            console.error('获取默认地址失败:', error);
        }
    },

    showBuyForm() {
        // 如果没有默认地址，直接显示地址表单


        this.setData({
            buyFormVisible: true
        })
    },

    onBuyFormClose() {
        this.setData({
            buyFormVisible: false
        });

        // 重置规格选择
        this.resetSpecSelection();
    },

    /**
     * 重置规格选择
     */
    resetSpecSelection() {
        
    },

    /**
     * 显示地址表单
     */
    showAddressForm() {
        this.setData({
            showAddressForm: true
        });
    },

    /**
     * 关闭地址表单
     */
    closeAddressForm() {
        this.setData({
            showAddressForm: false
        });
        this.resetAddressForm();
    },

    /**
     * 重置地址表单
     */
    resetAddressForm() {
        this.setData({
            addressForm: {
                name: '',
                phone: '',
                province: '',
                city: '',
                district: '',
                detail: '',
                region: '',
                isDefault: true
            }
        });
    },

    /**
     * 表单字段变化
     */
    onFieldChange(e) {
        const field = e.currentTarget.dataset.field;
        const value = e.detail;
        this.setData({
            [`addressForm.${field}`]: value
        });
    },

    /**
     * 默认地址开关变化
     */
    onDefaultChange(e) {
        this.setData({
            'addressForm.isDefault': e.detail
        });
    },

    /**
     * 显示地区选择器
     */
    showRegionPicker() {
        this.setData({ showRegion: true });
    },

    /**
     * 关闭地区选择器
     */
    closeRegionPicker() {
        this.setData({ showRegion: false });
    },

    /**
     * 地区选择确认
     */
    onRegionConfirm(e) {
        const { values } = e.detail;
        const region = values.map(item => item.name).join(' ');

        this.setData({
            'addressForm.province': values[0].name,
            'addressForm.city': values[1].name,
            'addressForm.district': values[2].name,
            'addressForm.region': region,
            showRegion: false
        });
    },

    /**
     * 保存地址
     */
    async saveAddress() {
        const { addressForm } = this.data;

        // 表单验证
        if (addressForm.name === '') {
            wx.showToast({
                title: '请输入收货人姓名',
                icon: 'none'
            });
            return;
        }

        if (addressForm.phone === '') {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none'
            });
            return;
        }

        if (!addressForm.province || !addressForm.city || !addressForm.district) {
            wx.showToast({
                title: '请选择所在地区',
                icon: 'none'
            });
            return;
        }

        if (addressForm.detail === '') {
            wx.showToast({
                title: '请输入详细地址',
                icon: 'none'
            });
            return;
        }

        try {
            const result = await AddressService.addAddress({
                name: addressForm.name,
                phone: addressForm.phone,
                province: addressForm.province,
                city: addressForm.city,
                district: addressForm.district,
                detail: addressForm.detail,
                isDefault: addressForm.isDefault,
                showLoading: true
            });

            if (result.success) {
                wx.showToast({
                    title: '添加成功',
                    icon: 'success'
                });

                this.closeAddressForm();
                // 重新获取默认地址
                this.getDefaultAddress();
                // 显示购买表单
                this.setData({
                    buyFormVisible: true
                });
            } else {
                wx.showToast({
                    title: result.message || '添加失败',
                    icon: 'none'
                });
            }

        } catch (error) {
            console.error('保存地址失败:', error);
            wx.showToast({
                title: '添加失败',
                icon: 'none'
            });
        }
    },

    /**
     * 选择地址
     */
    selectAddress() {
        wx.navigateTo({
            url: '/pages/i/address'
        });
    },

    onSpecListClick(e) {
        const { ku } = e.currentTarget.dataset;
        this.setData({
            selectedSku: ku
        });
    },

    onQuantityChange(e) {
        this.setData({
            quantity: e.detail
        })
    },

    /**
     * 立即购买
     */
    async onBuyClick() {
        const { selectedSku, quantity, defaultAddress } = this.data;

        // 检查是否已选择规格
        if (!selectedSku) {
            wx.showToast({
                title: '请先选择商品规格',
                icon: 'none'
            });
            return;
        }

        // 检查库存
        if (quantity > selectedSku.stock) {
            wx.showToast({
                title: `库存不足，当前库存: ${selectedSku.stock}`,
                icon: 'none'
            });
            return;
        }

        // 检查地址
        if (!defaultAddress || !defaultAddress.id) {
            wx.showToast({
                title: '请先选择收货地址',
                icon: 'none'
            });
            return;
        }

        try {
            let buyForm = {
                goods_id: this.data.goods.id,
                quantity: quantity,
                address_id: defaultAddress.id,
                sku_id: selectedSku.id, // 添加SKU ID
                unit_price: selectedSku.price, // 添加单价
                express_type: this.data.expressType,
                pick_up_point_id: this.data.expressType === 'pickUpPoint' ? this.data.defaultPickUpPoint.id : 0

            };


            const res = await GoodsService.buyGoods(buyForm);
            if (res.success) {

                // 关闭购买表单
                this.setData({
                    buyFormVisible: false
                });

                // 购买成功后跳转到支付页面
                wx.showLoading({
                    title: '去支付...',
                    mask: true,
                    complete: () => {
                        setTimeout(() => {
                            wx.hideLoading();
                            wx.navigateTo({
                                url: `/store/pages/goods/pay?order_id=${res.data.order_id}`
                            });
                        }, 1000);
                    }
                });
            } else {
                wx.showToast({
                    title: res.message,
                    icon: 'none'
                });
            }
        } catch (error) {
            console.error('购买失败:', error);
            wx.showToast({
                title: '购买失败，请稍后重试',
                icon: 'none'
            });
        }
    },

    /**
     * 选择配送方式
     */
    onExpressTypeChange(e) {
        const type = e.currentTarget.dataset.type;
        this.setData({
            expressType: type
        });
    },

    showAddToCart() {
        this.setData({
            addToCartVisible: true
        });
    },

    onCloseCart() {
        this.setData({
            addToCartVisible: false
        });
    },

    async onAddToCart() {
        const { selectedSku, quantity, selectSpecs, specs } = this.data;
        if (!selectedSku) {
            wx.showToast({
                title: '请先选择商品规格',
                icon: 'none'
            });
            return;
        }

        if (quantity > selectedSku.stock) {
            wx.showToast({
                title: `库存不足，当前库存: ${selectedSku.stock}`,
                icon: 'none'
            });
            return;
        }

        try {
            let buyForm = {
                goods_id: this.data.goods.id,
                quantity: quantity,

                specs: selectSpecs,
                sku_id: selectedSku.id, // 添加SKU ID
                unit_price: selectedSku.price, // 添加单价

            };

            console.log(buyForm);

            const res = await CartService.addToCart(buyForm);
            if (res.success) {
                wx.showToast({
                    title: '加入购物车成功',
                    icon: 'success'
                });
            }
            else {
                wx.showToast({
                    title: res.message,
                    icon: 'none'
                });
            }
        } catch (error) {
            wx.showToast({
                title: '加入购物车失败',
                icon: 'none'
            });
        }
    },

    toCart() {
        wx.navigateTo({
            url: '/store/pages/cart/index'
        });
    },

    onChange(e) {
        this.setData({
            timeData: e.detail,
        });
    },

    onBack() {
        wx.navigateBack({
            delta: 1
        });
    }
})